package com.gxuwz.icefrede.filter;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//创建拦截器，判断用户是否登录，如果未登录，则重定向到登录页面
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        // 如果用户未登录，重定向到登录页面
        if (user == null) {
            // 保存请求的URL以便登录后重定向回来
            session.setAttribute("redirectUrl", request.getRequestURI());
            response.sendRedirect(request.getContextPath() + "/backend/pages/login.html");
            return false;
        }
        return true;
    }
}

